#include "log_exp_def.hpp"
#include "log_exp_impl.hpp"


//Features as per Andres' WACV paper

inline
opt_feat::opt_feat(const std::string in_path, 
		   const std::string in_actionNames,  
		   const std::string in_feat_path,
		   const int in_col, 
		   const int in_row)
:path(in_path), actionNames(in_actionNames), feat_path(in_feat_path), col(in_col), row(in_row), n_samples_tr(17), n_samples_te(8)
{
  THRESH = 0.000001;
}

///Training
inline
void
opt_feat::training()
{
  calc_features();
  
}

///Testing
inline
void
opt_feat::testing(){
  
  log_exp log_exp1;
  double acc = 0; //accuracy
  
  
  mat log_covMte;
  mat log_covMtr;
  
  std::string type;
  
  type = "test";    
  //   
  //   ///Testing con training
  //   //type = "train";    
  //   //num_samples = n_samples_tr;
  //   
  std::stringstream tmp_ss;
  tmp_ss << path << actionNames;
  actions.load(tmp_ss.str());
  //actions.print("All actions");
  int n_test = actions.n_rows*n_samples_te;
  int n_train = actions.n_rows*n_samples_tr;
  
  rowvec ave_dist;
  rowvec train_labels;
  ave_dist.set_size(n_train);
  train_labels.set_size(n_train);
  
  for (uword act = 0 ; act < actions.n_rows; ++act) {
    
    cout << "Doing: " << actions(act) << endl;
    std::stringstream tmp_ss2;
    tmp_ss2 << path << actions(act)<<"/" <<type << "/"<< type <<"_list.txt";
    //cout << tmp_ss2.str()<< endl;
    //getchar();
    videos.load(tmp_ss2.str());
    //videos.print("All videos");
    field<mat>  field_log_covs;
    int count;
    
    for (uword vi = 0; vi <videos.n_rows; ++vi ){
      
      //Initializing
      //cout << "Video: " << vi << endl;
      ave_dist.zeros();
      //cout << "Size: " << covs.size() << endl;
      std::stringstream tmp_ss3;
      tmp_ss3 << path << actions(act)<<"/" << type << "/"<<  videos(vi);
      
      // Calculating covariance descriptor for current video
      //cout << "Calculating Covariance Descriptor for video " << endl;
      feature_video(tmp_ss3.str()); 
      int num_covs = covs.size();
      int k = 0;
      
      for (uword tr = 0; tr< actions.n_rows; ++tr) // 
       { 
	 for (uword v_tr = 0; v_tr<n_samples_tr; ++v_tr) 
	 {
	   std::stringstream tmp_train;
	   tmp_train << "./" << "flow_features/train" << "/log_"<<  actions(tr)<< "_"<< v_tr+1; // vi Starting at 1;
	   //cout << "Loading: " << tmp_train.str() << endl;
	   field_log_covs.load(tmp_train.str() );
	   
	   count =0;
	   train_labels(k) = tr;
	   //cout<< train_labels << endl;
	   for (uword ci_tr = 0; ci_tr<field_log_covs.n_rows; ++ci_tr)//cov_i for training video
 	{
	  log_covMtr = field_log_covs(ci_tr);
	  
	  for (uword ci_te = 0; ci_te < num_covs; ++ci_te) // Cada de una estas covarianzas son de un video de prueba
 	  {
	    //cout << "Cov: " << ci_te << endl;
	    //cout << "num_covs= " << i << endl;
	    //cov_desc = covs.at(ci_te);
	    log_covMte = log_exp1.log_matrix(covs.at(ci_te));  
	    ave_dist (k) += norm( log_covMte - log_covMtr ,"fro");
	    //ave_dist(k)+=1;
	    count +=1;
	  }
	}
	
	
	//cout << "count: " << count << endl;
	ave_dist(k)/=count;
	//ave_dist.print("ave_dist");
	k++;
	//getchar();
	 }
	 //getchar();
       }
       //ave_dist.print("ave_dist");
       //getchar();
       uword  index;
       double min_val = ave_dist.min(index);
       
       uword  est_class = train_labels(index);
       //cout << "index = " << index << ". Label is: " << train_labels(index) << endl; 
       
       
       cout << "This video is " << actions(act) << " and was classified as class: " << actions(est_class ) << endl;
       
       if (est_class == act){
	 acc++;
	 
      }
      
    }
    
  }
   cout << "Performance: " << acc*100/n_test << " %" << endl;
}



inline
void // Modificado Julio 3 usando mas descriptors por video.
opt_feat::calc_features() // Este solo sirve para entreamiento, no para validacion. 
{
  std::string type;
  int num_samples;
  
  
  type = "train";    
  num_samples = n_samples_tr;
  
  
  std::stringstream tmp_ss;
  tmp_ss << path << actionNames;
  actions.load(tmp_ss.str());
  //actions.print("All actions");
  
  
  for (uword act = 0 ; act < actions.n_rows; ++act) {
    
    std::stringstream tmp_ss2;
    tmp_ss2 << path << actions(act)<<"/" <<type << "/"<< type <<"_list.txt";
    //cout << tmp_ss2.str()<< endl;
    //getchar();
    videos.load(tmp_ss2.str());
    //videos.print("All videos");
    
    
    
    for (uword vi = 0; vi <videos.n_rows; ++vi ){ 
      std::stringstream tmp_ss3;
      tmp_ss3 << path << actions(act)<<"/" << type << "/"<<  videos(vi);
      //cout << tmp_ss3.str()<< endl;
      
      //features(count,0) = feature_video(tmp_ss3.str(), act);
      feature_video(tmp_ss3.str());
      save(act, vi);
    }
  }
}

inline
void
opt_feat::save(uword act, uword vi)
{
  field<mat>  field_covs;
  int num_covs = covs.size();
  field_covs.set_size(num_covs); // Column1: Cov Matrices, Column2: labels
  log_exp log_exp1;
  
  //cout << "num_covs: " << num_covs << endl;
  for (uword i=0; i<num_covs; ++i)
  {
    
    field_covs(i) = log_exp1.log_matrix(covs.at(i));
  }
  
  std::stringstream tmp_ss4;
  tmp_ss4 << feat_path << "train" << "/log_" << actions(act) << "_"<< vi+1; // vi Starting at 1
  cout << "Saving in" << tmp_ss4.str()<< endl;
  field_covs.save(tmp_ss4.str());
  
}


inline 
void
opt_feat::feature_video(std::string one_video)
{
  covs.clear();
  int num_covs;
  num_covs = 0;
  
  cv::VideoCapture capVideo(one_video);
  //cout << one_video << endl;
  //double fps = capVideo.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video
  //cout << "Frame per seconds : " << fps << endl;
  
  //cv::namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
  
  //double frmcount = capVideo.get(CV_CAP_PROP_FRAME_COUNT);
  //cout << "# of frames is: " << frmcount << endl;
  
  if( !capVideo.isOpened() )
  {
    cout << "Video couldn't be opened" << endl;
    return;
  }
  
  cv::Mat prevgray, gray, flow, cflow, frame, prevflow;
  cv::Mat ixMat, iyMat, ixxMat, iyyMat;
  //cv::namedWindow("My Video", 1);
  running_stat_vec<vec> stats_video(true);
  //cout << "Frame: ";
  int t = 0;
  int N_vectors = 0;
  int n_segm = 0;
  for(;;){
    
    
    //capVideo >> frame;
    
    bool bSuccess = capVideo.read(frame); // read a new frame from video
    
    if (!bSuccess) //if not success, break loop
      	{
	  //cout << "Cannot read the frame from video file" << endl;
	  break;
	}
	t++;
    cv::cvtColor(frame, gray, CV_BGR2GRAY);
    
    if( prevgray.data )
    {
      //cout << "Cuando entra aca?? en t= " << t << endl;
      cv::calcOpticalFlowFarneback(prevgray, 
				   gray, 
				   flow, 
				   0.5, //pyr_scale
				   3,   //levels
				   9,   //winsize
				   1,   //iterations
				   5,   //poly_n
				   1.1, //poly_sigma
				   0);  //flags
      //cv::calcOpticalFlowFarneback(bl_currentImg, bl_nextImg, flow, 0.5,  3, 5, 3, 5, 1.2, 0); 
      //cv::cvtColor(prevgray, cflow, CV_GRAY2BGR);
      //drawOptFlowMap(flow, cflow, 8, 1.5, CV_RGB(0, 255, 0));
      //cv::imshow("flow", cflow);
      
      
      cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1);
      cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1);
      cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1);
      cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1);
      
      float  ux = 0, uy = 0, vx = 0,  vy = 0;
      float u, v;
      //cout << "Llega a ciclo de Pixels???" << endl;
      //cout << "col: " << col << "- row " << row << endl;
      
      //printing frame number
      //cout << " " << t;
      if( prevflow.data )
      {
	
	if (n_segm == 19)
	{
	  //cout << "n_segm= " << n_segm;
	  //cout << ". N_vectors = " << N_vectors;
	  mat cov = stats_video.cov();
	  if (N_vectors > col*row/20)
	  {
	    //Following Mehrtash suggestions as per email dated June26th 2014
	    //cov.print("cov");
	    
	    cov = 0.5*(cov + cov.t());
	    vec D;
	    mat V;
	    eig_sym(D, V, cov);
	    uvec q1 = find(D < THRESH);
	    if (q1.n_elem>0)
	    {
	      for (uword pos = 0; pos < q1.n_elem; ++pos)
	      {
		D( q1(pos) ) = THRESH;
	      }
	      //cout << "***cov_hat***" << endl;
	      cov = V*diagmat(D)*V.t();  //
	    }  
	    
	    covs.push_back(cov);
	    num_covs++;
	    
	  }
	  else{
	    //cout << ". Covariance discarded.";
	  }
	  
	  stats_video.reset();
	  N_vectors = 0;
	  n_segm = 0;
	  //cout << " num_covs= " << num_covs << ". Label is: " << act <<endl;
	}
	
	
	for (uword x = 0 ; x < col ; ++x ){
	  for (uword y = 0 ; y < row ; ++y ) {
	    
	    vec features_one_pixel(15);
	    u = flow.at<cv::Vec2f>(y, x)[0];
	    v = flow.at<cv::Vec2f>(y, x)[1];
	    
	    //cout << "x= " << x << " - y= " << y << endl;
	    // x grad
	    //cout << " x y grad" << endl;
	    float ix = ixMat.at<float>(y, x);
	    //cout << " y grad" << endl;
	    float iy = iyMat.at<float>(y, x);
	    
	    // grad direction &  grad magnitude
	    //cout << "grad direction &  grad magnitude" << endl;
	    float gd = std::atan2(std::abs(iy), std::abs(ix));
	    float gm = std::sqrt(ix * ix + iy * iy);
	    
	    // x second grad
	    //cout << "x y  second grad " << endl;
	    float ixx = ixxMat.at<float>(y, x);
	    // y second grad
	    float iyy = iyyMat.at<float>(y, x);
	    
	    //du/dt
	    float ut = u - prevflow.at<cv::Vec2f>(y, x)[0];
	    // dv/dt
	    float vt = v - prevflow.at<cv::Vec2f>(y, x)[1];
	    
	    //// divergence &  vorticity
	    //cout << "divergence &  vorticity" << endl;
	    if (x>0 && y>0 )
	    {
	      ux = u - flow.at<cv::Vec2f>(y, x - 1)[0];
	      uy = u - flow.at<cv::Vec2f>(y - 1, x)[0];
	      vx = v - flow.at<cv::Vec2f>(y, x - 1)[1];
	      vy = v - flow.at<cv::Vec2f>(y - 1, x)[1];
	    }
	    //int x_submat = x + rec.x;
	    //int y_submat = y + rec.y;
	    //cout << x_submat << "&" << y_submat << endl;
	    
	    
	    
	    features_one_pixel  << x << y << t << abs(ix) << abs(iy) << abs(ixx) 
	    << abs(iyy) << gm << gd <<  u << v << abs(ut) 
	    << abs(ut) << (ux - vy)  << (vx - uy);
	    //features_one_pixel.t().print("Features Current Pixel: ");
	    //getchar();
	    
	    
	    if (!is_finite( features_one_pixel ) )
	    {
	      cout << "It's not FINITE... continue???" << endl;
	      getchar(); 
	    }
	    
	    // Plotting Moving pixels
	    //cout << " " << gm;
	    if (gm>40) // Empirically set to 40
			    {
			      //frame.at<cv::Vec3b>(y,x)[0] = 0;
			      //frame.at<cv::Vec3b>(y,x)[1] = 0;
			      //frame.at<cv::Vec3b>(y,x)[2] = 255;
			      stats_video(features_one_pixel);
			      N_vectors++;
			      
			    }
			    //cout << stats_video.cov() << endl;
	    //cout << stats_video.mean() << endl;
	  }
	}
	n_segm++;
      }
    }
    if(cv::waitKey(30)>=0)
      break;
    //cout << " t: " <<t;
      std::swap(prevgray, gray);
      std::swap(prevflow, flow);//aca esta el problema.... cuando hay flow????
      
      
      //cv::imshow("color", frame);
      //cv::waitKey();
  } 
  
  //cout << "Num_cov: " << num_covs << endl;
}


	
